## Sid Meier's Civilization 4
## Copyright Firaxis Games 2005
##
## TechConquest by Bhruic
## Updated by TheLopez
##

from CvPythonExtensions import *
import CvUtil
import PyHelpers
import Popup as PyPopup
import CvConfigParser

# globals
gc = CyGlobalContext()

# Change the value to true if technology should be handed completely over from
# the conquered city to their new owners.
# Default value is false
g_bCompleteTechnologyDiscovery = false

# Increase or decrease the value to change the number of or part of 
# technologies conquered cities will hand over to their new owners.
# Default value is 1
g_iTechnologyTransferCount = 1

# Change the value to true if the amount of technologies conquered cities will
# hand over to their new owners should be random.
# Default value is false
g_bRandomTechnologyTransferAmount = false

# Change the value to true if the conquering civilization can receive 
# technology without the appropriate prerequisites or ignore their civilization
# technology restrictions.
# Default value is false
g_bTechnologyTransferIgnorePrereq = false

# Change the value to false if full technology transfer should be allowed. By 
# setting the value to true this will force players to spend at least one turn
# researching pillaged technology.
# Default value is true
g_bDisableFullTechnologyTransfer = true

# Increase or decrease the value to change the base technology transfer 
# percentage amount.
# Default value is 25
g_iBaseTechnologyTransferPercent = 25

# Increase or decrease the value to change the percent amount per city 
# population that will be used to transfer technology to the new owners of
# the conquered city.
# Default value is 5
g_iPercentagePerCityPopulation = 5


def loadConfigurationData():
	global g_bCompleteTechnologyDiscovery
	global g_iTechnologyTransferCount
	global g_bRandomTechnologyTransferAmount
	global g_bTechnologyTransferIgnorePrereq
	global g_bDisableFullTechnologyTransfer
	global g_iBaseTechnologyTransferPercent
	global g_iPercentagePerCityPopulation 
	
	config = CvConfigParser.CvConfigParser("ViSa_v3.ini")

	if(config != None):
		g_bCompleteTechnologyDiscovery = config.getboolean("Enhanced Tech Conquest", "Complete Technology Discovery", False)
		g_iTechnologyTransferCount = config.getint("Enhanced Tech Conquest", "Technology Transfer Count", 1)
		g_bRandomTechnologyTransferAmount = config.getboolean("Enhanced Tech Conquest", "Random Technology Transfer Amount", False)
		g_bTechnologyTransferIgnorePrereq = config.getboolean("Enhanced Tech Conquest", "Technology Transfer Ignore Prereq", False)
		g_bDisableFullTechnologyTransfer = config.getboolean("Enhanced Tech Conquest", "Disable Full Technology Transfer", True)
		g_iBaseTechnologyTransferPercent = config.getint("Enhanced Tech Conquest", "Base Technology Transfer Percent", 25)
		g_iPercentagePerCityPopulation = config.getint("Enhanced Tech Conquest", "Percentage Per City Population", 5)

	
class EnhancedTechConquest:

	def onCityAcquired(self, argsList):
		iOldCityOwner, playerType, objCity, bConquest, bTrade = argsList

		# Return immediately if the city was not conquered		
		if (not bConquest):
			return
			
		# Get the map random object
		objMapRand = gc.getGame().getMapRand()
		
		# Get the conquerer's team
		objNewTeam = gc.getTeam(objCity.getOwner())

		# Get the conquering player
		objPlayer = gc.getPlayer(objCity.getOwner())

		# Get the old city owner
		objOldCityOwner = gc.getPlayer(iOldCityOwner)

		discoveredTechList = []
		strDiscoveredTechs = ""
				
		# Go through and try to get as many technologies as allowed
		for i in range(g_iTechnologyTransferCount):
		
			# Get the possible technologies that could be transfered
			possibleTechnologyList = self.getPossibleTechnologyList(objOldCityOwner, objCity, discoveredTechList)
			
			# Return if there are no possible technologies that can be transfered 
			# to the new owners of the city.
			if(len(possibleTechnologyList) == 0):
				continue

			# Pick a technology randomly from the list				
			iRandTech = objMapRand.get(len(possibleTechnologyList), "TechConquest")

			# Get the total number of technology points that will be transfered 
			# to the new city owner
			iTotalTechPoints = self.getTechnologyTransferAmount(possibleTechnologyList[iRandTech], objNewTeam, objCity)
			
			# Increase the research progress for the new city owner
			objNewTeam.changeResearchProgress(possibleTechnologyList[iRandTech], iTotalTechPoints, objCity.getOwner())
		
			strDiscoveredTechs = strDiscoveredTechs + "\n\t\t" + gc.getTechInfo(possibleTechnologyList[iRandTech]).getDescription()
			
			discoveredTechList.append(possibleTechnologyList[iRandTech])

		strMessage = ""
		# Inform the player they got a new technology.
		if (strDiscoveredTechs != ""):
			strMessage = "From the inhabitants of %s, you learn some of the secrets of: %s" %(objCity.getName(), strDiscoveredTechs)
		# Inform the player they didn't get any new technologies
		else:
			strMessage = "You find nothing worth learning from the inhabitants of %s" %(objCity.getName())
		
		CyInterface().addMessage(objPlayer.getID(), True, 20, strMessage, "", 0, gc.getCivilizationInfo(objOldCityOwner.getCivilizationType()).getButton(), ColorTypes(0), objCity.getX(), objCity.getY(), True, True) 


	# Returns the amount of technology points of that should be transfered from 
	# the old owners of the city to the new owners of the city.
	def getTechnologyTransferAmount(self, iTechInfo, objNewTeam, objCity):

		# Return zero immediately if the tech info passed in is invalid
		if(iTechInfo < 0):
			return 0

		# Return zero immediately if the new team passed in is invalid
		if(objNewTeam == None):
			return 0

		# Return zero immediately if the new team passed in is invalid
		if(objNewTeam.isNone()):
			return 0

		# Return zero immediately if the city passed in is invalid
		if(objCity == None):
			return 0

		# Return zero immediately if the city passed in is invalid
		if(objCity.isNone()):
			return 0
						
		objMapRand = gc.getGame().getMapRand()
		iTechCost = objNewTeam.getResearchCost(iTechInfo)

		# Return the full tech cost if the mod has been configured to do so
		if(g_bCompleteTechnologyDiscovery):

			if(g_bDisableFullTechnologyTransfer):
				iTechCost -= 1
				
			return iTechCost


		# Get the percentage amount of tech points that is given by the population
		iPercent = objCity.getPopulation() * g_iPercentagePerCityPopulation
		
		iExtraTechPoints = 0
		
		# Get the base percentage amount of tech points
		iBaseTechPoints = int(iTechCost * (float(g_iBaseTechnologyTransferPercent)/100.0))
		
		if(g_bRandomTechnologyTransferAmount):
			iExtraTechPoints = objMapRand.get(iPercent, "TechConquest")
		else :
			iExtraTechPoints = int(iTechCost *  (float(iPercent)/100.0))
		
		# Get the total amount of tech points to be transfered
		iTotalTechPoints = iBaseTechPoints + iExtraTechPoints

		# Get the new teams current progress on the technology
		iCurrentTechPoints = objNewTeam.getResearchProgress(iTechInfo)
		
		if (iTotalTechPoints > (iTechCost - iCurrentTechPoints)):
			iTotalTechPoints = iTechCost

			if(g_bDisableFullTechnologyTransfer):
				iTotalTechPoints -= 1

		else:
			iTotalTechPoints = iCurrentTechPoints + iTotalTechPoints				

		return iTotalTechPoints
		
		
	# Returns the list of technologies the conquering player could get from 
	# their newly conquered city.
	def getPossibleTechnologyList(self, objOldCityOwner, objCity, discoveredTechList):

		possibleTechnologyList = []

		# Return an empty list if the old city owner passed in is invalid
		if(objOldCityOwner == None):
			return []

		# Return an empty list if the old city owner passed in is invalid
		if(objOldCityOwner.isNone()):
			return []

		# Return an empty list if the city passed in is invalid
		if(objCity == None):
			return []

		# Return an empty list if the city passed in is invalid
		if(objCity.isNone()):
			return []
		
		# Get the team from the old owner of the city
		objOldCityOwnerTeam = gc.getTeam(objOldCityOwner.getTeam())

		# Get the conquering player of the city
		objConquerer = gc.getPlayer(objCity.getOwner())

		# Get the conquering team of the city
		objConquererTeam = gc.getTeam(objCity.getOwner())
		
		# Go through each technology in the game
		for iTechInfo in range(gc.getNumTechInfos()):
			
			# CvUtil.pyPrint("%s %s %s" %(gc.getTechInfo(iTechInfo).getType(), objConquerer.canResearch(iTechInfo, False), g_bTechnologyTransferIgnorePrereq) ) 
			# Continue if the conquerer cannot research the technology
			if(not objConquerer.canResearch(iTechInfo, False) and not g_bTechnologyTransferIgnorePrereq):
				continue
			
			# Append the technology to the possible technology list if the old 
			# team had the technology and the conquering team doesn't have the 
			# technology
			if ((objOldCityOwnerTeam.isHasTech(iTechInfo)) and (not objConquererTeam.isHasTech(iTechInfo)) and iTechInfo not in discoveredTechList):
				#CvUtil.pyPrint("%s" %(gc.getTechInfo(iTechInfo).getType()))
				possibleTechnologyList.append(iTechInfo)

		return possibleTechnologyList				
